import { EventEmitter } from 'events'
import path from 'path'
import fs from 'fs-extra'

class Language extends EventEmitter {
  constructor(paths) {
    super()
    this.paths = paths
    this.languageData = null
    this.currentLanguage = 'en' // 默认英文

    this.init()
  }

  init() {
    // 加载默认语言
    this.loadLanguage(this.currentLanguage)
  }

  loadLanguage(lang) {
    try {
      // 修改路径读取逻辑
      const userLanguagePath = path.join(this.paths.userDataPath, 'language', `${lang}.json`);
      const defaultLanguagePath = path.join(__dirname, '../../../static/language', `${lang}.json`);

      let languagePath;
      if (fs.existsSync(userLanguagePath)) {
        languagePath = userLanguagePath;
      } else if (fs.existsSync(defaultLanguagePath)) {
        languagePath = defaultLanguagePath;
      } else {
        console.error(`Language file for ${lang} not found.`);
        return;
      }

      this.languageData = fs.readJsonSync(languagePath);
      this.currentLanguage = lang;
      console.log("设置语言后emit事件：language-changed",lang)
      this.emit('language-changed', this.languageData);
    } catch (err) {
      console.error(`Failed to load language file: ${err.message}`);
    }
  }

  setLanguage(lang) {
    console.log("设置语言：",lang)
    if (lang !== this.currentLanguage) {
      this.loadLanguage(lang)
    }
  }

  getString(key) {
    if (!this.languageData) return key
    return this.languageData[key] || key
  }

  /**
   * 获取当前设置的语言
   * @returns {string} 当前语言代码 ('en' 或 'zh')
   */
  getCurrentLanguage() {
    return this.currentLanguage || 'en'
  }
}

export default Language
